<template>
  <div style="margin-top: 100px">
    <!-- 地址开始 -->
    <h3 style="margin-bottom: 10px;display: inline-block">收货地址</h3>
    <el-button @click="dialogFormVisible = true;isAdd=true" style="margin-left: 85%"
               type="primary" size="small">增加新地址
    </el-button>
    <div v-for="(address,i) in addressList">
      <el-row style="margin-top: 10px">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-radio v-model="radio" :label="address.id">{{ address.receiver }}({{ address.phone }})</el-radio>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light">
            {{ address.province }}{{ address.city }}{{ address.area }}{{ address.detailAdd }}
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <span v-if="address.isDefault===1">默认地址</span>
            <el-button size="small" @click="updateAdd(i)" style="float: right">修改</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 地址结束 -->
    <!-- 确认商品开始 -->
    <h3 style="margin: 10px 0">商品清单</h3>
    <div>
      <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
      >
        <el-table-column
            prop="picture"
            label=""
            width="120">
          <template slot-scope="scope"><img style="width: 70px;" :src="scope.row.picture"></template>
        </el-table-column>
        <el-table-column
            prop="bookName"
            label="商品"
            width="240"
        >
          <template slot-scope="scope">{{ scope.row.bookName }}</template>
        </el-table-column>
        <el-table-column

            prop="degree"
            label="品相"
            width="200">
          <template slot-scope="scope">{{ scope.row.degree }}</template>
        </el-table-column>
        <el-table-column
            prop="price"
            label="单价"
            width="200"
            show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.price }}</template>
        </el-table-column>
        <el-table-column
            prop="count"
            label="数量"
            width="200"
            show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.count }}
          </template>
          <!--            <template slot-scope="scope">{{ scope.row.count }}</template>-->
        </el-table-column>
        <el-table-column
            prop="amount"
            label="金额"
            width="120"
            show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.amount = (scope.row.price * scope.row.count).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;height: 50px;; background-color: gainsboro;border-radius: 5px">

        <span style="position: relative; left: 400px;top: 12px"> 共 <span
            style="color: chocolate ;font-weight: bolder;font-size: larger">{{ checkCount }} </span>件商品</span>
        <span style="position: relative; left: 400px;top: 12px"> 合计(不含运费):
          <span style="color: chocolate ;font-weight: bolder;font-size: larger">¥ {{ allPrices }}</span></span>

        <el-button @click="createOrder"
                   style="background-color: chocolate;color: white;float: right;height: 50px;margin: 0">
          确认并提交订单
        </el-button>
      </div>
      <!-- Form -->
      <el-button type="text" @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button>

      <el-dialog title="收货地址" :visible.sync="dialogFormVisible">


        <el-form :model="form">

          <el-form-item label="所在地" :label-width="formLabelWidth">
            <el-cascader
                style="width: 325px"
                v-model="form.address"
                :options="options"
                :props="{value:'label'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" :label-width="formLabelWidth">
            <el-input v-model="form.detailAdd" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="收货人" :label-width="formLabelWidth">
            <el-input v-model="form.receiver" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" :label-width="formLabelWidth">
            <el-input v-model="form.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="设为非默认地址" :label-width="formLabelWidth">
            <el-select v-model="form.isDefault">
              <el-option :key="0"
                         label="否"
                         :value="0"/>
              <el-option :key="1"
                         label="是"
                         :value="1"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateAddress">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {mapState} from "vuex";
import router from "@/router";
import city from "../../../public/citys.json";

export default {
  data() {
    return {
      /*修改、新增地址表单*/
      addressId: 0,
      dialogFormVisible: false,
      form: {
        detailAdd: '',
        isDefault: ''
      },
      isAdd: false,
      formLabelWidth: '120px',
      //地址选择器
      options: city,
      /*商品数据*/
      num: 0,
      tableData: [],
      /*地址*/
      radio: '1',
      addressList: [],
    };
  },
  computed: {
    ...mapState(["userId"]),
    // 计算总金额
    allPrices: function () {
      let allAmount = 0
      for (let i = 0; i < this.tableData.length; i++) {
        allAmount += this.tableData[i].price * this.tableData[i].count
      }
      return allAmount.toFixed(2)
    },
    // 计算商品数量
    checkCount: function () {
      return this.tableData.length
    }
  },
  mounted() {
    //获取本地订单数据
    this.tableData = JSON.parse(localStorage.getItem("orderTemp"))
    console.log("本地读取到的商品信息:")
    console.log(this.tableData)
    this.updateAddressFromDB()
  },
  methods: {
    updateAdd(index) {
      console.log(index)
      console.log(this.addressList)
      this.dialogFormVisible = true
      this.isAdd = false
      this.form = this.addressList[index]
      this.addressId = this.addressList[index].id
      console.log(index)
    },
    //生成订单
    createOrder() {
      if (this.addressList.length === 0) {
        this.$message.warning("请选择送货地址哦")
        return
      }
      console.log("选中地址ID：")
      console.log(this.addressList[this.radio])
      console.log("创建订单待完成")
      // 发送创建订单请求
      let data = {
        userId: '',
        addressId: '',
        books: []
      }
      data.userId = this.userId
      data.addressId = this.radio
      data.books = this.tableData
      console.log("创建订单发送请求数据为： ")
      console.log(data)
      axios.post("/order/create", data).then(r => {
        console.log("创建订单返回数据：")
        console.log(r.data)
        if (r.data.state === 20000) {
          this.$message.success("订单创建完成~")
          //跳转支付页面
          router.push("/pay")
          // 删除本地商品数据 "orderTemp"
          localStorage.removeItem("orderTemp")
        }
      })
    },
    //修改地址信息
    updateAddress() {
      this.dialogFormVisible = false
      this.form.userId = this.userId
      console.log(this.form)
      if (this.isAdd) {
        axios.post("/user/address/" + this.userId, this.form).then(r => {
          if (r.data.state === 20000) {
            this.$message.success("添加地址成功~")
            this.updateAddressFromDB()
          }
        }).catch(e => console.log(e))
      } else {
        axios.post("/user/address/update/" + this.addressId, this.form).then(r => {
          if (r.data.state === 20000) {
            this.$message.success("修改地址成功~")
            this.updateAddressFromDB()
          }
        }).catch(e => console.log(e))
      }
    },
    updateAddressFromDB() {
      //获取用户地址信息
      axios.get("/user/address/" + this.userId).then(r => {
        if (r.data.state === 20000) {
          console.log("服务端的地址数据为：")
          console.log(r.data.data)
          this.addressList = r.data.data
          //设置默认选中默认地址
          for (let i = 0; i < this.addressList.length; i++) {
            if (this.addressList[i].isDefault === 1) {
              this.radio = this.addressList[i].id
              break
            }
          }
        }
      }).catch(e => console.log(e))
    }
  },


}
</script>

<style scoped>

</style>